﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Web;
using System.Drawing;
using System.Drawing.Imaging;

namespace TRPOP.Common
{
    /// <summary>
    /// CMSImageHelper
    /// </summary>
    public class CMSImageHelper : YorkBaseImageHelper
    {
       /// <summary>
       /// 图片上传
       /// </summary>
       /// <param name="MaxFileSize">上传最大值(字节)，为0不限制</param>
       /// <param name="path">传路径</param>
        /// <param name="WaterImage">水印图片(为空时不加水印)，相对位置</param>
       /// <param name="AllowType">允许的类型[例：jpg|jpeg|gif|png ]为空不限制</param>
       /// <param name="enumLoaction">图片位置</param>
       /// <returns></returns>
        public static AttachmentInfo CMSImageUpLoad(int MaxFileSize, string path, string WaterImage, string AllowType, CMSImageHelper.WaterPicLocation enumLoaction)
        {
            HttpFileCollection MyFileColl = HttpContext.Current.Request.Files;
            if (MyFileColl.Count > 0)
            {
                List<ImageInfo> oltImageInfo = new List<ImageInfo>();

                return UploadImage(MaxFileSize, AllowType, MyFileColl[0], path, false, true, WaterImage.IsEmpty() == false, WaterImage, oltImageInfo, enumLoaction);
            }
            else
            {
                AttachmentInfo info = new AttachmentInfo();
                info.ErrorDescription = "没有选择上传的文件";
                return info;
            }
        }
        
        /// <summary>
        /// 图片上传[强制图片的高度和宽度]
        /// </summary>
        /// <param name="MaxFileSize">上传最大值(字节)，为0不限制</param>
        /// <param name="path">传路径</param>
        /// <param name="WaterImage">水印图片(为空时不加水印)</param>
        /// <param name="AllowType">允许的类型[例：jpg|jpeg|gif|png ]为空不限制</param>
        /// <param name="intWidth"></param>
        /// <param name="intHeight"></param>
        /// <param name="enumLoaction">图片位置</param>
        /// <returns></returns>
        public static AttachmentInfo CMSImageUpLoad(int MaxFileSize, string path, string WaterImage, string AllowType, int intWidth, int intHeight, CMSImageHelper.WaterPicLocation enumLoaction)
        {
            HttpFileCollection MyFileColl = HttpContext.Current.Request.Files;
            if (MyFileColl.Count > 0)
            {
                List<ImageInfo> oltImageInfo = new List<ImageInfo>();
                ImageInfo oImageInfo = new ImageInfo();
                oImageInfo.Height = intHeight;
                oImageInfo.Width = intWidth;
                oImageInfo.IsAbsoluteResize = true;
                oImageInfo.SaveExtendName = intWidth + "×" + intHeight;
                oltImageInfo.Add(oImageInfo);
                if (WaterImage == "")
                {
                    return UploadImage(MaxFileSize, AllowType, MyFileColl[0], path, true, false, false, "", oltImageInfo, enumLoaction);
                }
                else
                {
                    return UploadImage(MaxFileSize, AllowType, MyFileColl[0], path, true, false, true, WaterImage, oltImageInfo, enumLoaction);
                }
            }
            else
            {
                AttachmentInfo info = new AttachmentInfo();
                info.ErrorDescription = "没有选择上传的文件";
                return info;
            }
        }

        /// <summary>
        /// 图片上传[等比压缩，即不强制转换图片的高度和宽度]
        /// </summary>
        /// <param name="MaxFileSize">上传最大值(字节)，为0不限制</param>
        /// <param name="path">传路径</param>
        /// <param name="WaterImage">水印图片(为空时不加水印)</param>
        /// <param name="AllowType">允许的类型[例：jpg|jpeg|gif|png ]为空不限制</param>
        /// <param name="intWidth">宽度</param>
        /// <param name="intHeight">高度</param>
        /// <param name="enumLoaction">水印位置</param>
        /// <returns></returns>
        public static AttachmentInfo CMSImageUpLoadAutomini(int MaxFileSize, string path, string WaterImage, string AllowType, int intWidth, int intHeight, CMSImageHelper.WaterPicLocation enumLoaction)
        {
            HttpFileCollection MyFileColl = HttpContext.Current.Request.Files;
            if (MyFileColl.Count > 0)
            {
                List<ImageInfo> oltImageInfo = new List<ImageInfo>();
                ImageInfo oImageInfo = new ImageInfo();
                oImageInfo.Height = intHeight;
                oImageInfo.Width = intWidth;
                oImageInfo.IsAbsoluteResize = false;
                oImageInfo.SaveExtendName = intWidth + "×" + intHeight;
                oltImageInfo.Add(oImageInfo);
                if (WaterImage == "")
                {
                    //是否需要缩放 //是否只保存缩略图
                    return UploadImage(MaxFileSize, AllowType, MyFileColl[0], path, true, false, false, "", oltImageInfo, enumLoaction);
                }
                else
                {
                    return UploadImage(MaxFileSize, AllowType, MyFileColl[0], path, true, false, true, WaterImage, oltImageInfo, enumLoaction);
                }
            }
            else
            {
                AttachmentInfo info = new AttachmentInfo();
                info.ErrorDescription = "没有选择上传的文件";
                return info;
            }
        }

        /// <summary>
        /// 图片上传[等比压缩，即不强制转换图片的高度和宽度]
        /// </summary>
        /// <param name="MaxFileSize">文件大小限制</param>
        /// <param name="path">保存路径</param>
        /// <param name="WaterImage">水印位置</param>
        /// <param name="AllowType"></param>
        /// <param name="intWidth">长度</param>
        /// <param name="enumLoaction"></param>
        /// <returns></returns>
        public static AttachmentInfo CMSImageUpLoadAutomini(int MaxFileSize, string path, string WaterImage, string AllowType, int intWidth, CMSImageHelper.WaterPicLocation enumLoaction)
        {
            HttpFileCollection MyFileColl = HttpContext.Current.Request.Files;
            if (MyFileColl.Count > 0)
            {
                List<ImageInfo> oltImageInfo = new List<ImageInfo>();
                ImageInfo oImageInfo = new ImageInfo();
                oImageInfo.Width = intWidth;
                oImageInfo.IsAbsoluteResize = false;
                oltImageInfo.Add(oImageInfo);
                if (WaterImage == "")
                {
                    //是否需要缩放 //是否只保存缩略图
                    return UploadImage(MaxFileSize, AllowType, MyFileColl[0], path, true, false, false, string.Empty, oltImageInfo, enumLoaction);
                }
                else
                {
                    return UploadImage(MaxFileSize, AllowType, MyFileColl[0], path, true, false, true, WaterImage, oltImageInfo, enumLoaction);
                }
            }
            else
            {
                AttachmentInfo info = new AttachmentInfo();
                info.ErrorDescription = "没有选择上传的文件";
                return info;
            }
        }

        /// <summary>
        /// 上传过的图片另存缩略图
        /// 暂时不需要此功能
        /// </summary>
        /// <param name="strFilePath"></param>
        public static void ImgReSaveFromConfig(string strFilePath)
        {
            return;//暂时不需要此功能
            /*
            foreach (string strTemp in TRPOP.Config.SYSConfig.ImgReSave.Split(','))
            {
                if (strTemp.IsEmpty())
                    continue;
                if (strTemp.Contains("*"))
                {
                    int intWidth = int.Parse(strTemp.Split('*')[0].ToString());
                    int intHeight = int.Parse(strTemp.Split('*')[1].ToString());
                    string strNewPath = strFilePath.Insert(strFilePath.LastIndexOf("."), "_" + strTemp.Replace("*", "×"));
                    using (System.IO.StreamReader strmReader = new System.IO.StreamReader(strFilePath))
                    {
                        TRPOP.Common.ImageTools.ResizeImage(strmReader.BaseStream, strNewPath, intWidth, intHeight, TRPOP.Config.SYSConfig.blnPreserverAspectRatio, 80);
                    }
                }
            }
            */
        }

        #region 图片上传及处理的实际调用的方法

        /// <summary>
        /// 上传图片 详细的处理
        /// </summary>
        /// <param name="MaxFileSize">上传最大值(字节),为0不限制</param>
        /// <param name="AllowType">允许的类型[例：jpg|jpeg|gif|png ],为空不限制</param>
        /// <param name="postedFile">上传控件</param>
        /// <param name="upLoadForder">上传目录，相对于根目录，前不用加"/"</param>
        /// <param name="isResizeImage">是否需要缩放</param>
        /// <param name="isSaveResizeOnly">是否只保存缩略图</param>
        /// <param name="isWaterImage">是否需要加水印</param>
        /// <param name="WaterImage">水印图片，相对位置</param>
        /// <param name="oltImageInfo">缩放集合</param>
        /// <param name="enumLoaction">水印位置</param>
       /// <returns></returns>
        private static AttachmentInfo UploadImage(int MaxFileSize, string AllowType, HttpPostedFile postedFile, string upLoadForder, bool isResizeImage, bool isSaveResizeOnly, bool isWaterImage, string WaterImage, List<ImageInfo> oltImageInfo, CMSImageHelper.WaterPicLocation enumLoaction)
        {
            AttachmentInfo oaiInfo = new AttachmentInfo();
            string strRootFolder = "/";
            //文件名
            string strFileName = postedFile.FileName;
            //文件扩展名
            string strFileExtendName = strFileName.Substring(strFileName.LastIndexOf(".") + 1).ToLower();
            //文件真实类型
            string strFileType = postedFile.ContentType;
            //文件大小
            int intFileSize = postedFile.ContentLength;
            //是否出错
            bool blError = false;
            //文件上传的文件夹目录（绝对路径）
            string strFolderMapPath;
            if (!string.IsNullOrEmpty(upLoadForder))
            {
                strFolderMapPath = Util.GetMapPath(strRootFolder + upLoadForder + "/");
            }
            else
            {
                strFolderMapPath = Util.GetMapPath(strRootFolder);
            }
            //取当前时间的字符串                    
            string strNowTimeString = DateTime.Now.Year.ToString() + DateTime.Now.Month.ToString() + DateTime.Now.Day.ToString() + DateTime.Now.Hour.ToString() + DateTime.Now.Minute.ToString() + DateTime.Now.Second.ToString() + DateTime.Now.Millisecond.ToString();
            //文件的新名称
            string strNewFileName = strNowTimeString + intFileSize.ToString() + "." + strFileExtendName;
            //最终保存文件的路径
            string strFileMapPath = strFolderMapPath + "/" + strNewFileName;
            //返回的文件虚拟目录(相对路径)
            string strFileUploadPath = upLoadForder + "/" + strNewFileName;
            try
            {

                #region 类型判断(判断是否为系统允许的上传类型,判断文件大小)
                if (AllowType != "")
                {
                    if (strFileExtendName == "" || AllowType.IndexOf(strFileExtendName) == -1)
                    {
                        oaiInfo.ErrorDescription = "对不起，你上传的文件类型有误，允许的类型为" + AllowType;
                        blError = true;
                    }
                }
                if (MaxFileSize > 0)
                {
                    if (intFileSize == 0 || intFileSize > MaxFileSize)
                    {
                        oaiInfo.ErrorDescription = "对不起，上传文件最大为" + (MaxFileSize / 1000) + "K，请重新选择上传！";
                        blError = true;
                    }
                }
                if (blError)
                {
                    return oaiInfo;
                }
                #endregion
                Directory.CreateDirectory(strFolderMapPath);
                //如果需要缩放
                if (isResizeImage && oltImageInfo != null)
                {

                    //如果只保存缩略图
                    if (isSaveResizeOnly)
                    {
                        foreach (ImageInfo info in oltImageInfo)
                        {
                            string strResizeFileMapPath;

                            if (info.SaveExtendName.Equals(string.Empty))
                            {
                                strResizeFileMapPath = strFileMapPath;
                            }
                            else
                            {
                                strResizeFileMapPath = GetResizeFilePath(strFileMapPath, info.SaveExtendName);
                            }
                            if (info.IsAbsoluteResize)
                            {
                                ImageTools.ResizeImageAbsoluteTransparent(postedFile.InputStream, strResizeFileMapPath, info.Width, info.Height);
                                //ResizeImageAbsolute(postedFile.InputStream, strResizeFileMapPath, info.Width, info.Height);
                            }
                            else
                            {
                                ImageTools.ResizeImage(postedFile.InputStream, strResizeFileMapPath, info.Width, info.Height);
                            }
                        }

                    } //保存缩略图和原图
                    else
                    {
                        //如果需要加水印
                        if (isWaterImage)
                        {
                            DrawWaterImage(postedFile.InputStream, strFileMapPath, WaterImage, enumLoaction);
                        }
                        else
                        {
                            //保存原图
                            postedFile.SaveAs(strFileMapPath);
                        }
                        //保存缩略图

                        foreach (ImageInfo info in oltImageInfo)
                        {
                            string strResizeFileMapPath;

                            if (info.SaveExtendName.Equals(string.Empty))
                            {
                                strResizeFileMapPath = strFileMapPath;
                            }
                            else
                            {
                                strResizeFileMapPath = GetResizeFilePath(strFileMapPath, info.SaveExtendName);
                            }
                            if (info.IsAbsoluteResize)
                                ImageTools.ResizeImageAbsoluteTransparent(postedFile.InputStream, strResizeFileMapPath, info.Width, info.Height);
                            else
                                ImageTools.ResizeImage(postedFile.InputStream, strResizeFileMapPath, info.Width, info.Height);
                        }
                    }
                }
                else//不需要缩放
                {
                    //如果需要加水印
                    if (isWaterImage)
                    {
                        //保存加完水印的图
                        DrawWaterImage(postedFile.InputStream, strFileMapPath, WaterImage, enumLoaction);
                    }
                    else
                    {
                        //保存原图
                        postedFile.SaveAs(strFileMapPath);
                    }
                }
            }
            catch (Exception ex)
            {
                oaiInfo.ErrorDescription = "上传图片过程出现故障," + ex.Message;
            }
            //HttpContext.Current.Response.Write(strFileUploadPath);
            //附件属性
            oaiInfo.FileName = (strRootFolder + strFileUploadPath).Replace("//","/");
            oaiInfo.FileSize = intFileSize;
            oaiInfo.Attachment = strFileName.Substring(strFileName.LastIndexOf('\\') + 1);
            oaiInfo.FileType = strFileExtendName;
            return oaiInfo;
        }
        /*
         * 
         *  2011.07.18 lcheng 增加了水印位置可多选的功能
         *  详细查看一下代码
         * 
         */ 
        /// <summary>
        ///  图片水印的位置
        /// </summary>
        public enum WaterPicLocation
        {
            /// <summary>
            /// 左上角
            /// </summary>
            TopLeft = 1,
            /// <summary>
            /// 右上角
            /// </summary>
            TopRight = 2,
            /// <summary>
            /// 左下角
            /// </summary>
            BottomLeft = 3,
            /// <summary>
            /// 右下角
            /// </summary>
            BottomRight = 4,
            /// <summary>
            /// 偏下居中
            /// </summary>
            BottomCenter = 5
        }

        /// <summary>
        /// 加水印
        /// </summary>
        /// <param name="imageStream">图片流</param>
        /// <param name="strSavePath">保存路径</param>
        /// <param name="WaterImage">水印图片，相对位置</param>
        /// <param name="enumLoaction">水印位置</param>
        /// <returns></returns>
        public static bool DrawWaterImage(Stream imageStream, string strSavePath, string WaterImage, WaterPicLocation enumLoaction)
        {
            bool blnRtn = false;
            try
            {
                //获得图片源和水印图片源
                System.Drawing.Image image = System.Drawing.Image.FromStream(imageStream);
                //System.Drawing.Image imageWater = System.Drawing.Image.FromFile(HttpContext.Current.Server.MapPath(WaterImage));
                System.Drawing.Image imageWater = System.Drawing.Image.FromFile(Util.GetMapPath(WaterImage));
                //根据图片源创建BitMap
                Bitmap bitmap = new Bitmap(image, image.Width, image.Height);
                Graphics g = Graphics.FromImage(bitmap);

                //原图片和水印图片的对比
                bool blnIsWater = true;
                if (image.Width <= imageWater.Width || image.Height <= imageWater.Height || //如果水印图片比实际图片大的话，就不加水印了
                     image.Height < imageWater.Height * 3 //水印高度必须小于等于原始图片的1/3
                    )
                {
                    blnIsWater =  false;
                }
                //计算画框的宽度高度以及位置
                float rectWidth = imageWater.Width;
                float rectHeight = imageWater.Height;
                float rectX = image.Width - imageWater.Width;
                float rectY = image.Height - imageWater.Height;
                if (blnIsWater)
                {
                    //根据设置的位置变量，计算水印的位置
                    switch (enumLoaction)
                    {
                        case WaterPicLocation.BottomCenter:
                            rectY = (image.Height / 3) * 2;// 计算y坐标 2/3处
                            rectX = (image.Width - imageWater.Width) / 2;// 计算x坐标 中间的位置
                            break;
                        case WaterPicLocation.BottomLeft:
                            rectY = image.Height - imageWater.Height;//// 计算y坐标 下方
                            rectX = 0;//  计算x坐标 左侧的位置
                            break;
                        case WaterPicLocation.BottomRight:
                            rectY = image.Height - imageWater.Height;// 计算y坐标 下方
                            rectX = image.Width - imageWater.Width;// // 计算x坐标 右侧的位置
                            break;
                        case WaterPicLocation.TopLeft:
                            rectY = 0;// 计算y坐标 上方
                            rectX = 0;//  计算x坐标 左侧的位置
                            break;
                        case WaterPicLocation.TopRight:
                            rectY = 0;// 计算y坐标 上方
                            rectX = image.Width - imageWater.Width;// // 计算x坐标 右侧的位置
                            break;
                        default://默认 偏下居中
                            rectY = (image.Height / 3) * 2;// 计算y坐标 2/3处
                            rectX = (image.Width - imageWater.Width) / 2;// 计算x坐标 中间的位置
                            break;

                    }
                    //加上水印
                    g.DrawImage(imageWater, rectX, rectY, rectWidth, rectHeight);
                }


                //释放对象
                image.Dispose();
                imageWater.Dispose();

                //保存图片
                bitmap.Save(strSavePath, ImageFormat.Jpeg);

                //释放对象
                g.Dispose();
                bitmap.Dispose();
            }
            catch(Exception ex)
            {
                blnRtn = false;
                throw (ex);
            }
            return blnRtn;
        }

        #endregion

    }
}
